package org.dolphin.service.base;

import java.util.Locale;
import org.dolphin.service.base.CustomUser;
import org.dolphin.service.base.IdentitySupport;
import org.dolphin.service.base.LocaleSupport;
import org.dolphin.util.Nvl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class UserProfileHelper {
  public static String getUserFullname() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = "";
    if (authentication != null) {
      Object principal = authentication.getPrincipal();
      if (principal instanceof CustomUser) {
        username = ((CustomUser) principal).getFullname();
      } else {
        username = authentication.getName();
      }
    }
    return username;
  }

  public static String getUserIdentity() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !(authentication instanceof IdentitySupport)) {
      return null;
    }
    IdentitySupport support = (IdentitySupport) authentication;
    return support.getIdentity();
  }

  public static Locale getUserLocale() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Locale locale = Locale.getDefault();
    if (authentication == null || !(authentication instanceof LocaleSupport)) {
      return locale;
    }
    LocaleSupport localeSupport = (LocaleSupport) authentication;
    return Nvl.nvl(localeSupport.getLocale(), locale);
  }
}
